package cn.wolfcode.controller;

import cn.wolfcode.domain.Business;
import cn.wolfcode.domain.Business;
import cn.wolfcode.domain.Business;

import cn.wolfcode.qo.BusinessQueryObject;
import cn.wolfcode.service.IBusinessService;
import cn.wolfcode.util.FileUploadUtil;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.util.List;

@Controller
@RequestMapping("/business")
public class BusinessController {
    @Autowired
    private IBusinessService businessService;
    @RequestMapping("/list")
    @RequiredPermission(name="门店显示",expression ="business:list")
    public String list(@ModelAttribute("qo") BusinessQueryObject qo, Model model){
        PageInfo<Business> pageInfo = businessService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "/business/list";
    }
    @RequestMapping("/delete")
    @RequiredPermission(name="门店删除",expression ="business:delete")
    public String delete(Long id){
        if (id != null) {
            businessService.delete(id);
        }
        return "redirect:/business/list";
    }

    @Autowired
    private ServletContext servletContext;
    @RequestMapping("/saveOrUpdate")
    @RequiredPermission(name="门店新增/编辑",expression ="business:saveOrUpdate")
    public String saveOrUpdate(Business business, MultipartFile file) throws Exception {
        //判断是否为空文件
        if (file!=null&&file.getSize()>0) {
            //获取目录的绝对路径
            String realPath = servletContext.getRealPath("/");
            //判断原来是否有文件
            if (StringUtils.hasText(business.getLicenseImg())) {
                //删除原来的文件
                FileUploadUtil.deleteFile(realPath+business.getLicenseImg());
            }
            //文件最终存放的位置
            String url = FileUploadUtil.uploadFile(file, realPath);
            business.setLicenseImg(url);
        }
        if (business.getId() != null) {
            businessService.update(business,file);
        } else {
            businessService.insert(business,file);
        }
        return "redirect:/business/list";
    }
    @RequestMapping("/input")
    @RequiredPermission(name = "门店新增/编辑", expression = "business:saveOrUpdate")
    public String input(Long id, Model model) {
        if (id != null) {
            Business business = businessService.listOne(id);
            model.addAttribute("business", business);
        }
        return "/business/input";
    }
}
